/**
 * 阿里云百炼 AI API 服务（使用 DeepSeek-R1 模型）
 */

import Taro from '@tarojs/taro'

export interface ChatMessage {
  role: 'system' | 'user' | 'assistant'
  content: string
}

export interface StreamChunk {
  choices: Array<{
    delta: {
      reasoning_content?: string
      content?: string
    }
    finish_reason: string | null
  }>
}

export interface StreamCallbacks {
  onReasoning?: (text: string) => void
  onContent?: (text: string) => void
  onComplete?: () => void
  onError?: (error: Error) => void
}

class DeepSeekService {
  private apiKey: string = ''
  private apiUrl: string = 'https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions'
  private model: string = 'deepseek-r1-0528'

  // 设置API密钥
  setApiKey(key: string) {
    this.apiKey = key
  }

  // 发送流式聊天消息
  async chatStream(messages: ChatMessage[], callbacks: StreamCallbacks): Promise<void> {
    if (!this.apiKey) {
      throw new Error('请先设置阿里云百炼 API Key')
    }

    try {
      console.log('开始请求 AI，使用非流式模式（小程序兼容）')
      
      // 小程序环境下使用非流式响应
      const response = await Taro.request({
        url: this.apiUrl,
        method: 'POST',
        header: {
          'Content-Type': 'application/json',
          'Authorization': `Bearer ${this.apiKey}`
        },
        data: {
          model: this.model,
          messages: messages,
          stream: false,  // 改为非流式
          temperature: 0.7
        },
        timeout: 60000  // 60秒超时
      })

      console.log('API 响应状态码:', response.statusCode)
      console.log('API 响应数据:', response.data)

      if (response.statusCode === 200) {
        const data = response.data as any
        
        // 处理思考过程（如果有）
        if (data.choices && data.choices[0]) {
          const message = data.choices[0].message
          
          // DeepSeek-R1 可能在 message 中包含 reasoning_content
          if (message.reasoning_content && callbacks.onReasoning) {
            callbacks.onReasoning(message.reasoning_content)
          }
          
          // 处理回复内容
          if (message.content && callbacks.onContent) {
            callbacks.onContent(message.content)
          }
          
          callbacks.onComplete?.()
        } else {
          throw new Error('API 响应格式错误')
        }
      } else {
        throw new Error(`API请求失败: ${response.statusCode}，${JSON.stringify(response.data)}`)
      }
    } catch (error: any) {
      console.error('阿里云百炼 API Error:', error)
      console.error('错误详情:', error.errMsg || error.message)
      callbacks.onError?.(error as Error)
      throw new Error(error.errMsg || error.message || 'AI服务暂时不可用，请稍后再试。')
    }
  }

  // 发送非流式聊天消息（兼容旧接口）
  async chat(messages: ChatMessage[]): Promise<string> {
    if (!this.apiKey) {
      throw new Error('请先设置阿里云百炼 API Key')
    }

    let fullResponse = ''
    
    await this.chatStream(messages, {
      onContent: (text) => {
        fullResponse += text
      }
    })

    return fullResponse || '抱歉，我没有理解您的问题。'
  }

  // 创建文物对话（流式）
  async chatWithArtifactStream(
    artifactPrompt: string,
    userMessage: string,
    history: ChatMessage[] = [],
    callbacks: StreamCallbacks
  ): Promise<void> {
    const messages: ChatMessage[] = [
      {
        role: 'system',
        content: artifactPrompt
      },
      ...history,
      {
        role: 'user',
        content: userMessage
      }
    ]

    return this.chatStream(messages, callbacks)
  }

  // 创建文物对话（非流式，兼容旧接口）
  async chatWithArtifact(
    artifactPrompt: string,
    userMessage: string,
    history: ChatMessage[] = []
  ): Promise<string> {
    const messages: ChatMessage[] = [
      {
        role: 'system',
        content: artifactPrompt
      },
      ...history,
      {
        role: 'user',
        content: userMessage
      }
    ]

    return this.chat(messages)
  }
}

// 导出单例
export const deepSeekService = new DeepSeekService()

